package top.chukongxiang.project.base.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Objects;

/**
 * 跨域处理
 * @author 楚孔响
 * @version 1.0
 * @date 2022/2/15 11:09
 */
@Order(Ordered.HIGHEST_PRECEDENCE)
@Configuration
public class CorsConfig implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        HttpServletRequest reqs = (HttpServletRequest) req;
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Headers", "*");
        response.setHeader("Access-Control-Allow-Methods", "*");
        response.setHeader("Access-Control-Max-Age", "3600");
        List<String> headers = new ArrayList<>();
        Enumeration<String> headerNames = reqs.getHeaders("Access-Control-Request-Headers");
        if(Objects.nonNull(headerNames)) {
            while (headerNames.hasMoreElements()) {
                headers.add(headerNames.nextElement());
            }
        }
        response.setHeader("Access-Control-Allow-Origin", reqs.getHeader("origin"));
        response.setHeader("Access-Control-Max-Age", "3600");

        if ("OPTIONS".equalsIgnoreCase(reqs.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            chain.doFilter(req, res);
        }
    }

    @Override
    public void init(FilterConfig filterConfig) {
    }

    @Override
    public void destroy() {
    }

}
